var canvas = document.getElementById( "canvas" );
var context = canvas.getContext( "2d" );

var canvas2 = document.getElementById( "canvas2" );
var context2 = canvas2.getContext( "2d" );


var WIDTH = 1024;
var HEIGHT = 365;
var OFFSET = 50;
var LINE_HEIGHT = 10;
var RADIUS = 15;
var subwayLine;

initMap();
drawMap();

function initMap()
{
        var myStation1 = new Station( "اتصالات", "Etisalat", "Click on the picture for more information.", "images/station1-preview.png", "images/1.jpg", "images/11.jpg", "This is the first station and it is in Al Twar and Muhaisnah street. The Green Line is one of the two lines on the Dubai Metro network in Dubai, United Arab Emirates. It is currently opened in a limited phase, with 16 stations open from Etisalat to Dubai Healthcare City, it has Multi-level car park called Park and Ride terminal with capacity to accommodate 2,350 vehicles" );
        var myStation2 = new Station( "القصيص","Alqusais", "Click on the picture for more information.", "images/station2-preview.png", "images/2.jpg", "images/22.jpg", "It is a large community in Dubai (UAE). It is located in the Dira area of east Dubai. Al Qusais borders the localities of Hor Al Anz and Al Twar and is further subdivided into residential (Al Qusais) and industrial (Al Qusais Industrial Area) localities.This station will take you to Ministry of Education, General Department of Dubai Civil Defence, Al Twar Centre." );
        var myStation3 = new Station( "المنطقه الحره بمطار دبي", "Dubai Zone", "Click on the picture for more information.", "images/station3-preview.png", "images/3.gif", "images/33.jpg", "Welcome to Dubai Airport Freezone, ranked the Top Free Zone in the World by the Financial Times' fDi Magazine. Establish a Dubai free zone company with 100% foreign ownership at Dubai Airport Freezone. It is offering attractive packages for Dubai businesses set up within the city centre.This station will take you to Terminal 2 of Dubai Airport." );
        var myStation4 = new Station(  "النهده","Alnahda", "Click on the picture for more information.", "images/station4-preview.png", "images/4.jpg", "images/44.jpg", "Al Nahda, literally meaning The Awakening, is bordered to the south and east by Al Qusais, and to the west by Al Mamzar. It is bounded to the north by route E 11 (Al Ittihad Road) and to the south by a local road (204 Road). The community, currently under development, is largely industrial and sparsely populated. Like Muhaisnah. The Dubai Women's College is located in Al Nahda.This station will take you to Ministry of Public Works, Union Cooperative Society." );
        var myStation5 = new Station( "الاستاد","Stadium", "Click on the picture for more information.", "images/station5-preview.png", "images/5.jpg", "images/55.jpg", "Dubai Sports City is the vision of three leading entrepreneurs from the United Arab Emirates - Abdulrahim Al Zarooni, Abdulrahman Bukhatir and Abdulrahman Falaknaz to create one of the world's premier sporting destinations in line with the overall vision of HH Sheikh Mohammed to create world class sporting infrastructure in Dubai and making it a destination for the sporting world.This will take you to Al Ahli Club in Al Ghusais." );
        var myStation6 = new Station( "القياده","Al Qiyadah", "Click on the picture for more information.", "images/station6-preview.png", "images/6.png", "images/66.jpg", "The biggest elevated station on the Green Line is the Al Qiyadah Station along Al Ittihad Road near the Dubai Police General HQ. The station has a capacity to handle 11,000 passengers per hour in each direction.This will take you to Al Mulla Plaza, Dubai Police headquarters." );
        var myStation7 = new Station( "ابوهيل","Abu Hail", "Click on the picture for more information.", "images/station7-preview.png", "images/7.jpg", "images/77.jpg", "Abu Hail is a locality in Dubai, United Arab Emirates. Abu Hail is located in the region of Deira. The routes D 78, D 92, D 91 and D 82 form a periphery around the locality of Abu Hail.This will take you to Public schools, commercial centres." );
        var myStation8 = new Station( "ابوبكر الصديق","Abu Baker Al Siddique", "Click on the picture for more information.", "images/station8-preview.png", "images/8.jpg", "images/88.jpg", "In Dubai, United Arab Emirates a street is named after Abu Baker Al Siddique. It is a road starting from the foot of Al Maktoum Bridge in Deira. Clock Tower intersects Abu Baker Al Siddique with Al Maktoum Road, and as you go towards you will pass Al Riqqa Road, Al Muraqqabat Road, Salahuddin Road, Al Muteena Street, Al Rasheed Road up to Corniche Road. It is a busy road and considered main artillery in Dubai. Oyesan Dino Magkasi.This will take you to Hamrain Centre Marriott Hotel." );
        var myStation9 = new Station( "صلاح الدين","Salah Aldin", "Click on the picture for more information.", "images/station9-preview.jpg", "images/9.jpg", "images/99.jpg", "This will be our last stop and it will take you to Al Reef Mall, hotels and Al Maktoum hospital.I hope you enjoyed riding with us , and hope to see you again :) ");


        subwayLine = [ myStation9, myStation8, myStation7, myStation6, myStation5, myStation4, myStation3, myStation2, myStation1 ];

}


function drawMap()
{
	context.clearRect ( 0, 0, WIDTH, HEIGHT );
    //drawBackground();
    drawTitle();
    drawLine();
    drawStations();
}

function drawTitle()
{
        context.font = "11pt times";
        context.textAlign = "left";
        context.fillStyle ="green";
        context.fillText( "مترو دبي", 10, 20  );
        context.fillText("Dubai Metro Transit", 10, 40 );

}

function drawLine()
{
        var linewidth = WIDTH - OFFSET * 2;
        var startingX = OFFSET;
        var startingY = HEIGHT / 2;

        context.fillStyle = "green";
        context.fillRect(startingX, startingY, linewidth, LINE_HEIGHT);
}


function drawStations()
{
        var startingY = HEIGHT / 2;
        var width = WIDTH - OFFSET * 2;
        var intervals = width / ( subwayLine.length - 1);

       for( var i = 0; i < subwayLine.length; i = i + 1 )
         {
                // draw the circle
                context.beginPath();
                context.arc( OFFSET + i * intervals, startingY + RADIUS / 2, RADIUS, 0, 2 * Math.PI, false );
                context.fillStyle = "white";
                context.fill();
                context.strokeStyle = "green";
                context.stroke();
                
           if( subwayLine[i].isSelected )
                {
            	        context.fillStyle = "#9F1AB4";
                        context.fill();
                        context.strokeStyle = "green";
                        context.stroke();
                }
           
     		 
//your code to print the station name goes here
// draw the English and Chinese text
                context.fillStyle = "black";
                context.font = "11pt times";
                context.textAlign = "center";

                context.fillText( subwayLine[ i ].getNativeName(), OFFSET + i * intervals, startingY + 50 );
                context.fillText( subwayLine[ i ].getEnglishName(), OFFSET + i * intervals, startingY + 70 );
         }

}

canvas.onclick = function (evt)
{
	   
        var mouseX = evt.clientX - canvas.clientLeft - canvas.offsetLeft;
        var mouseY = evt.clientY - canvas.clientTop - canvas.offsetTop;

        var startingY = HEIGHT / 2;
        var width = WIDTH - OFFSET * 2;
        var intervals = width / ( subwayLine.length - 1);

     for( var i = 0; i < subwayLine.length; i = i + 1 )
        {
                //determine circle's center X
                var centerX = OFFSET + i * intervals;
                //determine circle's center Y
                var centerY = HEIGHT / 2;

          if ( ( mouseX - centerX ) * ( mouseX - centerX ) + ( mouseY - centerY ) * (mouseY - centerY ) < RADIUS * RADIUS )

          {
        	            currentIndex = [i];
        	            subwayLine[i].isSelected = true;
        	            document.getElementById( "sounds" ).play();                          
        	            animatePreviewInformation();
                        //this tells the function to stop once it finds a matching station
                        return;
                        
          }
            else
        {
                //resets the first canvas to all original colors when one does not click on a station.
                initMap();
                drawMap();
                
                
        }
       }
           if( mouseX >= WIDTH - 300 && mouseY <= 100 )
        {
        		
                drawInformationCanvas();
                
                
               
        }        
          else
        {
                //resets the first canvas to all original colors when one does not click on a station.
                initMap();
                drawMap();
        }
 if( mouseX >= WIDTH - 300 && mouseY <= 100 )
        {
        		
                drawInformationCanvas();
                
                
               
        }        
          else
        {
                //resets the first canvas to all original colors when one does not click on a station.
                initMap();
                drawMap();
        }
       
        
 }
 
function drawInformationCanvas()
{
        //displays the second canvas since it's not being displayed in css.
        document.getElementById( "canvas2" ).style.display = "inline";
        document.getElementById( "pic-sound" ).play();
        
    //draws the background of the second canvas
        var gradient = context2.createLinearGradient( 40, 100, 20, 175 );
        gradient.addColorStop( 0,"#F6F1AA" );
        gradient.addColorStop( 0.39, "#85B6E2" );
        context.fillStyle = gradient;
        context.fillRect( 0, 0 , WIDTH, HEIGHT );
        
    
    //writes the name of the station, both native and English, in the center of the canvas.
        context2.shadowColor = "green";
        context2.shadowBlur = 7;
        context2.shadowOffsetX = 5;
        context2.shadowOffsetY = 5;
        
        context2.fillStyle = "black";
        context2.font = "15pt Times";
        context2.textAlign = "center";
    
        context2.fillText( subwayLine[ currentIndex ].getNativeName(), WIDTH / 2, 40 );
        context2.fillText( subwayLine[ currentIndex ].getEnglishName(), WIDTH / 2, 70 );
        
        //calls the two pictures that needs to be displayed.
        context2.drawImage( subwayLine[ currentIndex ].getImage1(), 10, 100 );
        context2.drawImage( subwayLine[ currentIndex ].getImage2(), 710, 100 );
		
		
      
		
       
     // http: //www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
        function wrapText(context, text, x, y, maxWidth, lineHeight)
           {
             var cars = text.split("\n");

              for (var ii = 0; ii < cars.length; ii++) {

               var line = "";
               var words = cars[ii].split(" ");

                  for (var n = 0; n < words.length; n++) 
                  {
                   		var testLine = line + words[n] + " ";
                   		var metrics = context.measureText(testLine);
                   		var testWidth = metrics.width;

                   if (testWidth > maxWidth) 
                 {
                    context.fillText(line, x, y);
                    line = words[n] + " ";
                    y += lineHeight;
                  }
                   else
                  {  
                      line = testLine;
                  }
                } 

                  context2.fillText(line, x, y);
                  y += lineHeight;
   }
}

var maxWidth = 350;
var lineHeight = 20;
var x = WIDTH / 2;
var y = 125;
var text = subwayLine[ currentIndex ].getStationInfo();

context2.fillStyle = "black";
context2.font = "12pt times";

wrapText( context2, text, x, y, maxWidth, lineHeight );
}


canvas2.onclick = function( evt2 )
{
		
		
		var mouseX = evt2.clientX - canvas2.clientLeft - canvas2.offsetLeft;
        var mouseY = evt2.clientY - canvas2.clientTop - canvas2.offsetTop;
if( mouseX >= WIDTH - 300 && mouseY <= 100 )
        {
               canvas2.width = canvas2.width; 
               drawMap();

               
        }        
          else
        {
              	canvas2.width = canvas2.width;
                initMap();
                drawMap();
        }     
        document.getElementById( "canvas2" ).style.display = "none";
        
}




 
var previewInformationOpacity = 0;
var previewInformationOffsetY = 0;
var currentIndex = -1; //set in the onclick event when identifying clicked station


function animatePreviewInformation()
{
        context.globalAlpha = 1;
        drawMap();
        
        //applies to the descending image
        context.globalAlpha = previewInformationOpacity;
        //100 = image height, 300 = image width
        context.drawImage( subwayLine[ currentIndex ].getPreviewImage(), WIDTH - 300, previewInformationOffsetY - 100 );

        /* code for the other parts of the preview information here*/

        //display the native and English name for the station clicked.
        contextfillStyle = "black";
        context.font = "12pt times";
        context.textAlign = "center";
       
        context.fillText( subwayLine[ currentIndex ].getNativeName(), WIDTH / 2 + 50, previewInformationOffsetY - 60);
        context.fillText( subwayLine[ currentIndex ].getEnglishName(), WIDTH / 2 + 50, previewInformationOffsetY - 40);
        context.fillStyle = "black";
        context.font = "10pt times";
        context.textAlign = "left";
        context.fillText( subwayLine[ currentIndex ].getInformation(), WIDTH / 2 + 210, previewInformationOffsetY + 15 );
        previewInformationOffsetY = previewInformationOffsetY + 2;
        previewInformationOpacity = previewInformationOpacity + 0.2;
        
        if( previewInformationOffsetY <= 100 )
                {
                        window.requestAnimationFrame( animatePreviewInformation );
                }
        else
                {
                        previewInformationOpacity = 0;
                        previewInformationOffsetY = 0;
                    
                }
}

window.requestAnimationFrame = ( function()
		{
		        return          window.requestAnimationFrame       ||
		                        window.webkitRequestAnimationFrame ||
		                        window.mozRequestAnimationFrame    ||
		                        window.oRequestAnimationFrame      ||
		                        window.msRequestAnimationFrame     ||

		        function( callback )
		                        {
		                        window.setTimeout( callback, 1000 / 60 );
		                        };
		})();

